import { Message } from '../types';
import * as fs from 'fs';
import * as path from 'path';

export interface HistoryData {
  sessionId: string;
  timestamp: string;
  messages: Message[];
}

interface HistorySessionInfo {
  sessionId: string;
  fileName: string;
  filePath: string;
  timestamp: string;
  title: string;
  messageCount: number;
}

export class HistorySaver {
  private historyFilePath: string;
  private sessionId: string;
  private enabled: boolean;

  constructor(enabled: boolean = true) {
    this.enabled = enabled;
    this.sessionId = `session_${Date.now()}`;
    this.historyFilePath = path.join(process.cwd(), 'chat_history', `${this.sessionId}.json`);
    
    if (this.enabled) {
      this.ensureHistoryDirectory();
      console.log(`📁 会话ID: ${this.sessionId}`);
      console.log(`💾 历史记录将保存到: ${this.historyFilePath}`);
    }
  }

  private ensureHistoryDirectory() {
    const historyDir = path.dirname(this.historyFilePath);
    if (!fs.existsSync(historyDir)) {
      fs.mkdirSync(historyDir, { recursive: true });
      console.log(`📁 创建历史记录目录: ${historyDir}`);
    }
  }

  saveHistory(messages: Message[]) {
    if (!this.enabled) {
      return;
    }

    try {
      const historyData: HistoryData = {
        sessionId: this.sessionId,
        timestamp: new Date().toISOString(),
        messages: messages
      };
      
      fs.writeFileSync(this.historyFilePath, JSON.stringify(historyData, null, 2), 'utf8');
      console.log(`💾 历史记录已保存 (${messages.length} 条消息)`);
    } catch (error) {
      console.error('❌ 保存历史记录失败:', error);
    }
  }

  loadHistory(filePath: string): Message[] | null {
    try {
      if (!fs.existsSync(filePath)) {
        console.log('📂 历史记录文件不存在');
        return null;
      }

      const data = fs.readFileSync(filePath, 'utf8');
      const historyData: HistoryData = JSON.parse(data);
      
      console.log(`📚 加载历史记录: ${historyData.sessionId} (${historyData.messages.length} 条消息)`);
      return historyData.messages;
    } catch (error) {
      console.error('❌ 加载历史记录失败:', error);
      return null;
    }
  }

  listHistoryFiles(): string[] {
    const historyDir = path.join(process.cwd(), 'chat_history');
    
    if (!fs.existsSync(historyDir)) {
      return [];
    }

    return fs.readdirSync(historyDir)
      .filter(file => file.endsWith('.json'))
      .sort((a, b) => b.localeCompare(a)); // 按时间倒序
  }

  getHistoryList(): HistorySessionInfo[] {
    const historyFiles = this.listHistoryFiles();
    const historyList: HistorySessionInfo[] = [];

    for (const fileName of historyFiles) {
      try {
        const filePath = path.join(process.cwd(), 'chat_history', fileName);
        const data = fs.readFileSync(filePath, 'utf8');
        const historyData: HistoryData = JSON.parse(data);
        
        // 获取title - 从第一条用户消息截取（通常是第二条消息：system, user）
        let title = '无标题对话';
        const firstUserMessage = historyData.messages.find(msg => msg.role === 'user');
        if (firstUserMessage) {
          title = firstUserMessage.content.length > 30 
            ? firstUserMessage.content.substring(0, 30) + '...'
            : firstUserMessage.content;
        }

        historyList.push({
          sessionId: historyData.sessionId,
          fileName,
          filePath,
          timestamp: historyData.timestamp,
          title,
          messageCount: historyData.messages.length
        });
      } catch (error) {
        console.error(`❌ 读取历史文件失败: ${fileName}`, error);
      }
    }

    return historyList;
  }

  loadFullHistory(filePath: string): HistoryData | null {
    try {
      if (!fs.existsSync(filePath)) {
        console.log('📂 历史记录文件不存在');
        return null;
      }

      const data = fs.readFileSync(filePath, 'utf8');
      const historyData: HistoryData = JSON.parse(data);
      
      console.log(`📚 加载完整历史记录: ${historyData.sessionId} (${historyData.messages.length} 条消息)`);
      return historyData;
    } catch (error) {
      console.error('❌ 加载完整历史记录失败:', error);
      return null;
    }
  }

  loadHistoryBySessionId(sessionId: string): HistoryData | null {
    const historyFiles = this.listHistoryFiles();
    
    for (const fileName of historyFiles) {
      try {
        const filePath = path.join(process.cwd(), 'chat_history', fileName);
        const data = fs.readFileSync(filePath, 'utf8');
        const historyData: HistoryData = JSON.parse(data);
        
        if (historyData.sessionId === sessionId) {
          console.log(`📚 找到并加载历史记录: ${sessionId}`);
          return historyData;
        }
      } catch (error) {
        console.error(`❌ 读取历史文件失败: ${fileName}`, error);
      }
    }
    
    console.log(`❌ 未找到sessionId: ${sessionId} 的历史记录`);
    return null;
  }

  deleteHistory(filePath: string): boolean {
    try {
      if (fs.existsSync(filePath)) {
        fs.unlinkSync(filePath);
        console.log(`🗑️ 已删除历史记录: ${filePath}`);
        return true;
      }
      return false;
    } catch (error) {
      console.error('❌ 删除历史记录失败:', error);
      return false;
    }
  }

  setEnabled(enabled: boolean) {
    this.enabled = enabled;
    console.log(`💾 历史记录保存: ${enabled ? '已启用' : '已禁用'}`);
  }

  getSessionId(): string {
    return this.sessionId;
  }

  getHistoryFilePath(): string {
    return this.historyFilePath;
  }
}